//
// Created by v on 24-5-15.
//

#include <string.h>
#include "esp_log.h"
#include <time.h>
#include <esp_timer.h>
#include <errno.h>

#include "cm_broadcast_service.h"
#include "cm_broadcast_func.h"

#define TAG "broadservice"

typedef struct {
    CMBroadcastHandle broadcast_handle;
    int list_port;
    int broad_interval;
    int64_t last_time;
    int64_t send_count;
} CMBroadcastServiceHandle;

static CMBroadcastServiceHandle s_broadcast_service_handle;

int cm_broadcast_service_start(int port, int interval)
{
    memset(&s_broadcast_service_handle, 0, sizeof(s_broadcast_service_handle));
    int ret = cm_broadcast_init(&s_broadcast_service_handle.broadcast_handle, port);
    if (ret < 0)
    {
        ESP_LOGE(TAG, "broadcast failed ret = [%d]", ret);
        return -2;
    }
    s_broadcast_service_handle.broad_interval = interval;
    s_broadcast_service_handle.list_port = port;
    ret = cm_broadcast_socket_init_simple(s_broadcast_service_handle.broadcast_handle);
    if (ret < 0)
    {
        ESP_LOGE(TAG, "init simple error ret = [%d]", ret);
    }
//    ret = cm_broadcast_bind(s_broadcast_service_handle.broadcast_handle);
    return ret;
}

int cm_broadcast_service_stop()
{
    cm_broadcast_close(&s_broadcast_service_handle.broadcast_handle);
    memset(&s_broadcast_service_handle, 0, sizeof(s_broadcast_service_handle));
    return 0;
}

int cm_broadcast_service_send_data(const char *data, int len)
{
    int64_t now = esp_timer_get_time();
    if (now - s_broadcast_service_handle.last_time > s_broadcast_service_handle.broad_interval*1000000)
    {
        s_broadcast_service_handle.last_time = now;
        int ret = cm_broadcast_send(s_broadcast_service_handle.broadcast_handle, data, len);
        s_broadcast_service_handle.send_count++;
        if (ret < 0)
        {
            ESP_LOGE(TAG, "send error [%d][%s]", errno, strerror(errno));
        }
        ESP_LOGI(TAG, "send broadcast result [%d] send count [%lld]", ret, s_broadcast_service_handle.send_count);
    }
    return 0;
}

int cm_broadcast_service_recv_data(char *data, int *len)
{
    if (!len)
    {
        return -1;
    }
    int ret = cm_broadcast_recv(s_broadcast_service_handle.broadcast_handle, data, *len);
    if (ret > 0)
    {
        *len = ret;
    }
    return ret;
}
